#!/usr/bin/env python

FREQ_BUF_LEN = 8

from peak import F_SAMPLE, pulse_peak_gen

gen = pulse_peak_gen()
buf = []
freq_buf = []

while len(buf)+1 < 4:
    buf.append(gen.next()[0])

while True:
    buf.append(gen.next()[0])
    
    dist_buf = []
    dist_buf.append(buf[3] - buf[1])
    dist_buf.append(buf[2] - buf[0])
    dist_buf.append(2 * (buf[3] - buf[2]))
    dist_buf.append(2 * (buf[2] - buf[1]))
    
    dist_buf.sort()
    dist_avg = int((dist_buf[1] + dist_buf[2]) / 2)

    freq_buf.append(int(F_SAMPLE * 60.0 / dist_avg))
    if len(freq_buf) == FREQ_BUF_LEN:
        for i in range(0, dist_avg/2):
            print sum(freq_buf) / FREQ_BUF_LEN
        del freq_buf[0]
    
    del buf[0]
